/*
 * CTextureManager.cpp
 *
 *  Created on: Sep 6, 2011
 *      Author: welcome
 */

#include "CTextureManager.h"
namespace GGEngine {

TextureMap CTextureManager::textures;

CTextureManager::CTextureManager() {

}

CTextureManager::~CTextureManager() {

}

KDuint CTextureManager::getTexture(std::string filename, ExtType type, GLuint &textureName ) {

	CTexture texture;
	KDuint result = 0;

	TextureMap::iterator iter = textures.begin();
	iter = textures.find(filename);
	if (iter != textures.end()) {
		GLuint textureName = iter->second;
		glBindTexture(GL_TEXTURE_2D, textureName);
		return 0;
	}

	result = texture.loadTexture(filename.c_str(), type);

	if (result != 0)
	{
		return result;
	}

	glGenTextures(1, &textureName);


	glBindTexture(GL_TEXTURE_2D, textureName);

	glTexImage2D(GL_TEXTURE_2D, 0, texture.format, texture.width,
			texture.height, 0, texture.format, GL_UNSIGNED_BYTE,
			texture.pixelData);

	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	iter = textures.end();

	textures.insert(iter, pair<std::string, GLuint>(filename, textureName));

	return result;
}
GLvoid CTextureManager::deleteTexture(std::string textureName) {

	TextureMap::iterator iter = textures.begin();
	iter = textures.find(textureName);
	if (iter != textures.end() ) {
		glDeleteTextures(1, &iter->second);
		textures.erase(iter);
	}
}

GLvoid CTextureManager::deleteAllTextures() {
	TextureMap::const_iterator end = textures.end();
	for (TextureMap::const_iterator it = textures.begin(); it != end; it++) {
		glDeleteTextures(1, &it->second);
	}
	textures.clear();
}

}
